﻿using System;
using System.Web.Mvc;
using Mailer.Model.Repositories;
using System.Text.RegularExpressions;
using NHibernate;
using Mailer.Model;
using Mailer.Model.Types;
using NHibernate.Criterion;

namespace Mailer.Controllers
{
	[HandleError]
	public class ApplicationController : Controller
	{
		[Authorize]
		public ActionResult View(Guid id, int? page)
		{
			int pagesize = 5;
			int oo = 0;
			if (page.HasValue)
				oo = page.Value * pagesize;

			var sess = SessionUtilities.BeginSession();
			if (sess != null)
			{
				// kolla access			
				var app = ApplicationRepository.Get(id);
				ViewData["ID"] = app.ID;
				ViewData["Name"] = app.Name;
				ViewData["PublicID"] = app.PublicID;
				ViewData["Secret"] = app.Secret;
				ViewData["Lists"] = app.Lists;
				ViewData["Mails"] = sess.CreateCriteria<Mail>().Add(Expression.Eq("ApplicationID", app.ID)).AddOrder(Order.Desc("CreatedDate")).SetMaxResults(pagesize).SetFirstResult(oo).List<Mail>();
				//	app.Mails;//.Select()
				ViewData["Recipients"] = app.Recipients;
			}
			return base.View();
		}

		[Authorize]
		public ActionResult PartialMailListTable(Guid id, int? page)
		{
			int pagesize = 5;
			int oo = 0;
			if (page.HasValue)
				oo = page.Value * pagesize;


			var app = ApplicationRepository.Get(id);

			var sess = SessionUtilities.BeginSession();
			if (sess != null)
			{
				ViewData["ID"] = app.ID;

				// ViewData["Name"] = app.Name;
				// ViewData["PublicID"] = app.PublicID;
				// ViewData["Secret"] = app.Secret;
				// ViewData["Lists"] = app.Lists;

				ViewData["Mails"] = sess.CreateCriteria<Mail>().Add(Expression.Eq("ApplicationID", app.ID)).SetMaxResults(pagesize).SetFirstResult(oo).
						List<Mail>();

				// ViewData["Mails"] = app.Mails;

				// ViewData["Recipients"] = app.Recipients;

			}
			return base.View();
		}

		[Authorize]
		public ActionResult MailArchive(Guid id, int? page)
		{
			int pagesize = 5;
			int oo = 0;
			if (page.HasValue)
				oo = page.Value * pagesize;

			ISession sess = SessionUtilities.BeginSession();
			if (sess != null)
			{
				// kolla access			
				Application app = ApplicationRepository.Get(id);
				ViewData["ID"] = app.ID;
				ViewData["Name"] = app.Name;
				// ViewData["PublicID"] = app.PublicID;
				// ViewData["Secret"] = app.Secret;
				// ViewData["Lists"] = app.Lists;
				ViewData["Mails"] = app.Mails;// sess.CreateCriteria<Mail>().Add(Expression.Eq("ApplicationID", app.ID)).SetMaxResults(pagesize).SetFirstResult(oo).List<Mail>();
				//	app.Mails;//.Select()
				ViewData["Recipients"] = app.Recipients;
			}
			return base.View();
		}


		[Authorize]
		[AcceptVerbs(HttpVerbs.Get)]
		public ActionResult New()
		{
			return base.View();
		}

		[Authorize]
		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult New(string name, string shortname)
		{
			ActionResult res = null;

			Guid userid = Utilities.GetUserID(this);


			if (name.Length < 5)
			{
				ModelState.AddModelError("_FORM", "Name should be 5 characters or more.");
			}
			else if (shortname.Length < 5)
			{
				ModelState.AddModelError("_FORM", "Shortname should be 5 characters or more.");
			}
			else if (Regex.IsMatch("[^a-z0-9]", shortname))
			{
				ModelState.AddModelError("_FORM", "Shortname can only contain the characters: a-z and 0-9.");
			}
			else
			{
				// TODO: Check for duplicate shortnames!

				ISession sess = SessionUtilities.BeginSession();
				if (sess != null)
				{
					Guid appguid = Guid.Empty;

					using (ITransaction transaction = sess.BeginTransaction())
					{
						Mailer.Model.Types.Application a = new Mailer.Model.Types.Application();
						a.Name = name;
						a.ShortName = shortname;
						a.PublicID = Regex.Replace(Guid.NewGuid().ToString(), "[^a-z0-9]", "");//.Substring(0, 20);
						a.Secret = Regex.Replace(Guid.NewGuid().ToString(), "[^a-z0-9]", "");//.Substring(0, 20);		
						sess.Save(a);
						a.SetPropertyValue(sess, "trackingmode", "none");
						appguid = a.ID;

						Mailer.Model.Types.User u = sess.Get<Mailer.Model.Types.User>(userid);
						// Mailer.Model.Types.UserApplication ua = new Mailer.Model.Types.UserApplication();
						// ua.UserID = userid;
						u.Applications.Add(a);
						// ua.Application = a;
						sess.Save(u);

						res = RedirectToAction("Edit", "Application", new { ID = a.ID });

						transaction.Commit();
					}
					SessionUtilities.EndSession(sess);
				}
			}

			// If we got this far, something failed, redisplay form
			if (res == null)
				res = View();
			return res;
		}





		[Authorize]
		[AcceptVerbs(HttpVerbs.Get)]
		public ActionResult Edit(Guid id)
		{

			ISession sess = SessionUtilities.BeginSession();
			if (sess != null)
			{
				Mailer.Model.Types.Application a = sess.Get<Application>(id);
				// kolla rättigheter

				ViewData["ID"] = a.ID;
				ViewData["Name"] = a.Name;
				ViewData["PublicID"] = a.PublicID;
				ViewData["Secret"] = a.Secret;

				ViewData["userstylesheet"] = a.GetPropertyValue("userstylesheet");
				ViewData["userheadhtml"] = a.GetPropertyValue("userheadhtml");
				ViewData["usertophtml"] = a.GetPropertyValue("usertophtml");
				ViewData["userbottomhtml"] = a.GetPropertyValue("userbottomhtml");

				ViewData["senderemail"] = a.GetPropertyValue("senderemail");
				ViewData["sendername"] = a.GetPropertyValue("sendername");

				ViewData["recipientemail"] = a.GetPropertyValue("recipientemail");
				ViewData["recipientname"] = a.GetPropertyValue("recipientname");

				ViewData["replytoemail"] = a.GetPropertyValue("replytoemail");

				ViewData["language"] = a.GetPropertyValue("language");

				ViewData["trackingmode"] = a.GetPropertyValue("trackingmode");
				ViewData["trackingmailserver"] = a.GetPropertyValue("trackingmailserver");
				ViewData["trackingmailusername"] = a.GetPropertyValue("trackingmailusername");
				ViewData["trackingmailpassword"] = a.GetPropertyValue("trackingmailpassword");
				ViewData["trackingmailpublicaddress"] = a.GetPropertyValue("trackingmailpublicaddress");

				SessionUtilities.EndSession(sess);
			}

			return base.View();
		}


		[Authorize]
		[ValidateInput(false)]
		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult Edit(
			Guid id,
			string name,
			string userstylesheet,
			string usertophtml,
			string userbottomhtml,
			string userheadhtml,
			string senderemail,
			string sendername,
			string replytoemail,
			string recipientname,
			string recipientemail,
			string trackingmode,
			string trackingmailserver,
			string trackingmailusername,
			string trackingmailpassword,
			string trackingmailpublicaddress,
			string language
		)
		{
			ActionResult res = null;

			Guid userid = Utilities.GetUserID(this);

			if (name.Length < 5)
			{
				ModelState.AddModelError("_FORM", "Name should be 5 characters or more.");
			}
			else
			{
				// TODO: Check for duplicate shortnames!

				ISession sess = SessionUtilities.BeginSession();
				if (sess != null)
				{
					Guid appguid = Guid.Empty;

					using (ITransaction transaction = sess.BeginTransaction())
					{
						Mailer.Model.Types.Application a = sess.Get<Application>(id);
						// kolla rättigheter
						a.Name = name;
						//	a.ShortName = shortname;	

						sess.Save(a);

						a.SetPropertyValue(sess, "userstylesheet", userstylesheet);
						a.SetPropertyValue(sess, "usertophtml", usertophtml);
						a.SetPropertyValue(sess, "userbottomhtml", userbottomhtml);
						a.SetPropertyValue(sess, "userheadhtml", userheadhtml);

						a.SetPropertyValue(sess, "senderemail", senderemail);
						a.SetPropertyValue(sess, "sendername", sendername);
						a.SetPropertyValue(sess, "recipientemail", recipientemail);
						a.SetPropertyValue(sess, "recipientname", recipientname);
						a.SetPropertyValue(sess, "replytoemail", replytoemail);

						a.SetPropertyValue(sess, "language", language);

						a.SetPropertyValue(sess, "trackingmode", trackingmode);
						a.SetPropertyValue(sess, "trackingmailserver", trackingmailserver);
						a.SetPropertyValue(sess, "trackingmailusername", trackingmailusername);
						a.SetPropertyValue(sess, "trackingmailpassword", trackingmailpassword);
						a.SetPropertyValue(sess, "trackingmailpublicaddress", trackingmailpublicaddress);

						transaction.Commit();

						res = RedirectToAction("View", "Application", new { ID = a.ID });
					}

					SessionUtilities.EndSession(sess);
				}
			}

			// If we got this far, something failed, redisplay form
			if (res == null)
				res = View();

			return res;
		}

	}
}
